package com.bear.plan.jdbc.imp;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import com.bear.PlatFormDao.plan.PlanDetailDao;
import com.bear.model.entity.plan.Plan;
import com.bear.model.entity.plan.PlanDetail;

@Repository
public class PlanDetailDaoImp implements PlanDetailDao{

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	public List<PlanDetail> getPlanDetailByPlanid(int id) {
		String sqlStr = "select id,whatyoudo,complete,dodate,planid " +
				" from plandetail where planid=?";
		final List<PlanDetail> plandetails = new ArrayList<PlanDetail>();
		jdbcTemplate.query(sqlStr,new Object[]{id},
				new RowCallbackHandler() {
					@Override
					public void processRow(ResultSet rs) throws SQLException {
							PlanDetail plandetail = new PlanDetail();
							plandetail.setId(rs.getInt("id"));
							plandetail.setWhatyoudo(rs.getString("whatyoudo"));
							plandetail.setComplete(rs.getInt("complete"));
							plandetail.setDodate(rs.getDate("dodate"));
							plandetail.setPlanid(rs.getInt("planid"));
							plandetails.add(plandetail);
					}
				});
		return plandetails;
	}

	@Override
	public Plan getPlanById(Integer planid) {
		String sqlStr = "select id,detail,userid,percent " +
				" from plan where id=?";
		final Plan plan = new Plan();
		jdbcTemplate.query(sqlStr,new Object[]{planid},
				new RowCallbackHandler() {
					@Override
					public void processRow(ResultSet rs) throws SQLException {
						plan.setId(rs.getInt("id"));
						plan.setDetail(rs.getString("detail"));
						plan.setUserid(rs.getInt("userid"));
						plan.setPercent(rs.getInt("percent"));
					}
				});
		return plan;
	}

	@Override
	public void addDetail(PlanDetail detail) {
		String sqlStr = "insert into plandetail (whatyoudo,complete,dodate,planid)" +
				" values(?,?,?,?) ";
		Object[] args= {detail.getWhatyoudo(),detail.getComplete(),detail.getDodate(),detail.getPlanid()};
		jdbcTemplate.update(sqlStr,args);
		
	}

	@Override
	public void updateComplete(Integer planid) {
		String sql = "update plan set percent=(select sum(complete) from plandetail where planid=?) where id=?";
		Object[] args= {planid,planid};
		jdbcTemplate.update(sql,args);
	}

	@Override
	public void deleteDetail(int detailid) {
		String sql = "delete from plandetail where id="+detailid;
		jdbcTemplate.execute(sql);
	}

}
